package com.horizon.cloud.distribute.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class CuratorZKClientFactory {

    /**
     * 简单方式创建curatorframework
     * @param connectionString
     * @return
     */
    public static CuratorFramework createSimple(String connectionString) {
        //重试策略：第一次重试等待1s,第二次重试等待2s，第三次重试等待4s
        //第一个参数：等待时间基础单位，秒,1000表示以秒为单位
        //第二个参数：最大重试次数，3表示重试3次，间隔1s,2s,4s
        ExponentialBackoffRetry exponentialBackoffRetry = new ExponentialBackoffRetry(1000,3);
        //简单获取curatorFramework
        //第一个参数:zk的链接地址
        //第二个参数:重试策略
        return CuratorFrameworkFactory.newClient(connectionString, exponentialBackoffRetry);
    }

    /**
     * builder方式创建curatorFramework
     * @param connectionString
     * @param retryPolicy
     * @param connectionTimeMs
     * @param sessionTimeoutMs
     * @return
     */
    public static CuratorFramework createWithOptions(String connectionString,
                                                     RetryPolicy retryPolicy,
                                                     int connectionTimeMs,
                                                     int sessionTimeoutMs) {
        //builder方式创建curatorframwork
        return CuratorFrameworkFactory.builder().connectString(connectionString)
                .retryPolicy(retryPolicy).connectionTimeoutMs(connectionTimeMs)
                .sessionTimeoutMs(sessionTimeoutMs).build();
    }

}
